<?php

namespace app\common\model;

use think\facade\Db;

class User extends Base
{

    // 设置当前模型对应的完整数据表名称
    protected $table = 'user';

    /**
     * 获取列表
     */
    public static function getList($where = [], $field = '*', $order = '', $pageSize = "15")
    {
        $list = self::where($where)
            ->field($field)
            ->order($order)
            ->paginate(['list_rows' => $pageSize, 'query' => request()->param()]);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count'] = $list->total();
        $data['last_page'] = $list->toArray()['last_page'];
        $data['page'] = $page;
        return $data;
    }

    /**
     * 获取单条数据
     */
    public static function getInfo($where = [], $field = '*')
    {
        $data = self::where($where)
            ->field($field)
            ->find();
        return $data;
    }

    /**
     * 欧气值升级
     */
    public static function ou_qi_level_up($user_id, $money, $type = 1)
    {
        if ($type == 1) {
            $ou_qi = round($money * 100, 2);
            self::changeOuQi($user_id, $ou_qi, 2, '消费赠送');
        }
//        #符合升级的权益
        // $level_info = QyLevel::field('id,level,title,number')
        //     ->whereNull('deltime')
        //     ->order('id desc')
        //     ->select()->toArray();
        $return = [];
        for($i=0; $i<20;$i++) {
            $user_info = Db::name('user')->field('ou_qi,ou_qi_level')->where('id', $user_id)->find();
            if ($user_info['ou_qi'] < 1) {
                break;
            }
            $next_level = $user_info['ou_qi_level'] + 1;
            if ($next_level <= 75) {
                $next_info = QyLevel::where(['level'=>$next_level])->field('id, level, title, number')->find();
                if ($user_info['ou_qi'] >= $next_info['number']) {
                    $return[] = self::field('ou_qi_level')->where('id', $user_id)->update(['ou_qi_level' => $next_level]);
                    $ret = self::changeOuQi($user_id, -$next_info['number'], 3, '升级减少', $next_level.'级');
                    $return = array_merge($return, $ret);
                }
            }
        }
      
        return $return;

        // foreach ($level_info as $k => $v) {
        //     if ($user_info['ou_qi'] >= $v['number'] && $v['level'] > $user_info['ou_qi_level']) {
        //         $cha_ou_qi = bcsub((string)$user_info['ou_qi'],(string)$v['number'],2);
        //         self::field('ou_qi_level')->where('id', $user_id)->update(['ou_qi_level' => $v['level']]);
        //         self::changeOuQi($user_id, -$v['number'], 3, '升级减少', $v['level'],  '级');
        //         break;
        //     }
        // }
    }

    /**
     * 用户欧气值变化
     * @param $user_id
     * @param $change_money
     * @param $type
     * @param $content
     * @param int $share_uid
     * @param string $other
     * @return int
     */
    public static function changeOuQi($user_id, $change_money, $type, $content, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('ou_qi')->find($user_id);
        $money = $user_info['ou_qi'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['other'] = $other;
        $res[] = ProfitOuQi::insert($arr);
        $res[] = $user_info->save(['ou_qi' => $money]);
        return $res;
    }

    public static function ou_qi_level($ou_qi_level, $ou_qi)
    {
        if ($ou_qi_level == 0) {
            $number = QyLevel::field('level,title')
                ->where('level', '=', 1)
                ->whereNull('deltime')
                ->value('number');
            if ($ou_qi != 0) {
                $jindu = round($number / $ou_qi * 100);
            } else {
                $jindu = 0;
            }

            return ['level' => 0, 'title' => '暂无权益', 'cha' => $number, 'jindu' => $jindu];
        } else {
            $level_info = QyLevel::field('level,title')
                ->where('level', '=', $ou_qi_level)
                ->whereNull('deltime')
                ->find();

            $xia_level_info = QyLevel::field('number')
                ->where('level', '=', $ou_qi_level + 1)
                ->whereNull('deltime')
                ->find();

            if ($xia_level_info) {
                $level_info['cha'] = $xia_level_info['number'] - $ou_qi;
                $level_info['jindu'] = round($ou_qi / $xia_level_info['number'] * 100);
                return $level_info;
            } else {
                $level_info['cha'] = '-1';
                $level_info['jindu'] = 100;
                return $level_info;
            }
        }
    }

    /**
     * 用户市集余额变化
     * @param $user_id
     * @param $change_money
     * @param $type 1后台充值 2在线充值 3抽赏消费 4背包兑换 5推荐奖励
     * @param $content
     * @param int $share_uid
     * @param string $other
     * @return int
     */
    public static function changeMoney2($user_id, $change_money, $type, $content = '', $share_uid = 0, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('money2')->find($user_id);
        $money = $user_info['money2'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['share_uid'] = $share_uid;
        $arr['other'] = $other;
        $res[] = ProfitMoney2::insert($arr);
        $res[] = $user_info->save(['money2' => $money]);
        return $res;
    }


    /**
     * 用户潮币变化
     * @param $user_id
     * @param $change_money
     * @param $type 1后台充值 2抽赏消费 3开券获得
     * @param $content
     * @param int $share_uid
     * @param string $other
     * @return int
     */
    public static function changeIntegral($user_id, $change_money, $type, $content = '', $share_uid = 0, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('integral')->find($user_id);
        $money = $user_info['integral'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['share_uid'] = $share_uid;
        $arr['other'] = $other;
        $res[] = ProfitIntegral::insert($arr);
        $res[] = $user_info->save(['integral' => $money]);
        return $res;
    }

    /**
     * 判断是否发积分 发券
     * @param $order
     */
    public static function is_integral_coupon($order)
    {
        $goods = Goods::where('id', '=', $order['goods_id'])->find();
        $res = [];
        #开启发积分
        if ($goods['integral_is'] == 1 && $order['price'] > 0) {
            $res[] = self::changeScore($order['user_id'], $order['price'], 4, '抽奖奖励');
        }
        #开启发券
        if ($goods['coupon_is'] == 1) {
            $d_coupon_num = OrderList::field('goodslist_money')->where([['order_id', '=', $order['id']], ['goodslist_money', '>=', 100], ['goodslist_money', '<', 500]])->select();
            $config = getConfig("base");

            foreach ($d_coupon_num as $k => $v){
                $coupon = [];
                $coupon['title'] = "普通赏券";
                $coupon['num'] = $v['goodslist_money'];
                $coupon['level'] = 4;
                $coupon['kl_num'] = $config['coupon_d_xz_max'];
                $res[] = self::insert_coupon($order, $coupon);
            }

            $c_coupon_num = OrderList::field('goodslist_money')->where([['order_id', '=', $order['id']], ['goodslist_money', '>=', 500], ['goodslist_money', '<', 2000]])->select();
            foreach ($c_coupon_num as $k => $v){
                $coupon = [];
                $coupon['title'] = "高级赏券";
                $coupon['num'] = $v['goodslist_money'];
                $coupon['level'] = 3;
                $coupon['kl_num'] = $config['coupon_c_xz_max'];
                $res[] = self::insert_coupon($order, $coupon);
            }

            $b_coupon_num = OrderList::field('goodslist_money')->where([['order_id', '=', $order['id']], ['goodslist_money', '>=', 2000], ['goodslist_money', '<', 5000]])->select();
            foreach ($b_coupon_num as $k => $v){
                $coupon = [];
                $coupon['title'] = "终极赏券";
                $coupon['num'] = $v['goodslist_money'];
                $coupon['level'] = 2;
                $coupon['kl_num'] = $config['coupon_b_xz_max'];
                $res[] = self::insert_coupon($order, $coupon);
            }

            $a_coupon_num = OrderList::field('goodslist_money')->where([['order_id', '=', $order['id']], ['goodslist_money', '>=', 5000]])->select();
            foreach ($a_coupon_num as $k => $v){
                $coupon = [];
                $coupon['title'] = "特级赏券";
                $coupon['num'] = $v['goodslist_money'];
                $coupon['level'] = 1;
                $coupon['kl_num'] = $config['coupon_a_xz_max'];
                $res[] = self::insert_coupon($order, $coupon);
            }
        }

        if (!$res) {
            $res[] = 1;
        }
        return $res;
    }

    /**
     * 用户积分变化
     * @param $user_id
     * @param $change_money
     * @param $type 1后台充值 2抽赏消费 3升级获得 4抽赏奖励
     * @param $content
     * @param int $share_uid
     * @param string $other
     * @return int
     */
    public static function changeScore($user_id, $change_money, $type, $content, $share_uid = 0, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('score')->find($user_id);
        $money = $user_info['score'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['share_uid'] = $share_uid;
        $arr['other'] = $other;
        $res[] = ProfitScore::insert($arr);
        $res[] = $user_info->save(['score' => $money]);
        return $res;
    }
    
    //用户优惠券
    public static function insert_coupon($order, $coupon)
    {
        //自己获得80%
        $percentage = 80;
        $own = $coupon['num'] * ($percentage / 100);
        //其他人获得20%
        $percentage = 20;
        $other = $coupon['num'] * ($percentage / 100);

        $data = [
            'user_id' => $order['user_id'],
            'level' => $coupon['level'],
            'title' => $coupon['title'],
            'num' => $coupon['num'],
            'status' => 1,
            'type' => 1,
            'from_id' => $order['id'],
            'own' => intval($own),
            'own2' => intval($own),
            'other' => intval($other),
            'other2' => intval($other),
            'kl_num' => $coupon['kl_num'],
            'kl_num2' => $coupon['kl_num'],
            'addtime' => time(),
            'updatetime' => time(),
        ];
        $result = UserCoupon::insert($data);
        return $result;
    }

    /**
     * 分销奖励
     * @param $order
     */
    public static function distribution($order)
    {
        #微信支付金额
        $price = $order['price'];
        $fx_bili = (int)getConfig("base")['fx_bili'];
        if ($price > 0 && $fx_bili > 0) {
            $fx_bili = $fx_bili / 100;
            $jiangli = bcmul("$price", "$fx_bili", 2);
            if ($jiangli > 0) {
                $pid = self::field('id')->where('id', '=', $order['user_id'])->value('pid');
                if ($pid) {
                    $res[] = self::changeMoney($pid, $jiangli, 5, '推荐奖励', $order['user_id'], '奖励比例:' . $fx_bili);
                }
            }
            if (empty($res)) {
                $res = 1;
            }
            return $res;
        } else {
            $res = 1;
            return $res;
        }
    }

    /**
     * 用户余额变化
     * @param $user_id
     * @param $change_money
     * @param $type 1后台充值 2在线充值 3抽赏消费 4背包兑换 5推荐奖励
     * @param $content
     * @param int $share_uid
     * @param string $other
     * @return int
     */
    public static function changeMoney($user_id, $change_money, $type, $content = '', $share_uid = 0, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('money')->find($user_id);
        $money = $user_info['money'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['share_uid'] = $share_uid;
        $arr['other'] = $other;
        $res[] = ProfitMoney::insert($arr);
        $res[] = $user_info->save(['money' => $money]);
        return $res;
    }

    public static function changeDraw($user_id, $change_money, $type, $content = '', $share_uid = 0, $other = '')
    {
        if ($change_money == 0) {
            return 1;
        }
        #用户信息
        $user_info = self::field('draw_num')->find($user_id);
        $money = $user_info['draw_num'];
        $money = bcadd("$money", "$change_money", 2);
        $arr = [];
        $arr['user_id'] = $user_id;
        $arr['change_money'] = $change_money;
        $arr['money'] = $money;
        $arr['type'] = $type;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        $arr['share_uid'] = $share_uid;
        $arr['other'] = $other;
        $res[] = ProfitDraw::insert($arr);
        $res[] = $user_info->save(['draw_num' => $money]);
        return $res;
    }

    /*
        扣除抽奖券
    */

    public function getCommissionMoneyAttr($value, $data)
    {
        $money = ProfitMoney::field('change_money')
            ->where('user_id', '=', $data['pid'])
            ->where('type', '=', 5)
            ->where('share_uid', '=', $data['id'])
            ->where('change_money', '>', 0)
            ->sum('change_money');
        return $money;
    }


}